import axios from 'axios'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(111)
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const { success, message } = res
    if (success === true) {
      // 完全成功
      // 直接把后台返回的数据对象给逻辑页面
      return res
    } else {
      // 如果本次响应逻辑状态码未成功，就返回错误提示消息给逻辑页面
      return Promise.reject(message)
    }
  },
  error => {
    if (error.response.status === 401) {
      store.commit('user/RESET_STATE')
      router.replace(`/login?theurl=${encodeURIComponent(router.currentRoute.fullPath)}`)
    }
    return Promise.reject(error)
  }
)

// 导出 自定义的axios实例方法
export default service
